﻿using System;
using System.Configuration;
using ReadyApps.Common;

namespace ReadyApps.Data
{
    /// <summary>
    /// Provides access to the data provider for the wiki control.
    /// </summary>
    class WikiDataProviderFactory
    {
        #region Public Methods

        /// <summary>
        /// Gets an instance of the configured Wiki Data Provider.
        /// </summary>
        /// <returns>An object that implements the <see cref="ReadyApps.Data.IWikiDataProvider"/> interface</returns>
        public static IWikiDataProvider GetInstance()
        {
            TraceManager.BeginMethod(TraceComponent.DataProviderFactory, "GetInstance");

            IWikiDataProvider dataProvider = null;

            string typeName = ReadyAppsSettings.WikiDataProviderTypeName;
            string assembly = ReadyAppsSettings.WikiDataProviderAssembly;

            // If the assembly is empty, assume that it is in the currently running assembly, i.e., it is
            // one of the pre-packaged types within this assembly.
            if (string.IsNullOrEmpty(assembly))
            {
                dataProvider = (IWikiDataProvider)Activator.CreateInstance(Type.GetType(typeName));
            }
            else
            {
                dataProvider = (IWikiDataProvider)(Activator.CreateInstance(assembly, typeName).Unwrap());
            }

            string connectionString = ConfigurationManager.ConnectionStrings[ReadyAppsSettings.WikiConnectionStringName].ConnectionString;
            TraceManager.VariableValue(TraceComponent.DataProviderFactory, "ConnectionString", connectionString);
            dataProvider.SetConnectionString(connectionString);

            TraceManager.EndMethod(TraceComponent.DataProviderFactory, "GetInstance");
            return dataProvider;
        }

        #endregion
    }
}
